<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="text-title">用户管理</h1>
      <p class="text-caption">管理系统用户账号、权限和状态</p>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-controls">
        <input 
          v-model="searchQuery"
          class="apple-input"
          placeholder="搜索用户名、姓名、邮箱或员工编号..."
          @input="handleSearch"
        >
        
        <select v-model="filterDepartment" class="apple-input filter-select">
          <option value="">全部部门</option>
          <option v-for="dept in departments" :key="dept" :value="dept">
            {{ dept }}
          </option>
        </select>
        
        <select v-model="filterStatus" class="apple-input filter-select">
          <option value="">全部状态</option>
          <option value="active">激活</option>
          <option value="inactive">未激活</option>
          <option value="suspended">暂停</option>
          <option value="locked">锁定</option>
        </select>
      </div>
      
      <div class="action-controls">
        <button 
          class="apple-button apple-button--secondary"
          @click="showStatistics = true"
        >
          📊 统计信息
        </button>
        <button 
          class="apple-button apple-button--primary"
          @click="showCreateDialog = true"
        >
          新建用户
        </button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="users-container">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p class="text-body">加载中...</p>
      </div>

      <div v-else-if="users.length === 0" class="empty-state">
        <div class="empty-icon">👤</div>
        <h3 class="text-subheading">暂无用户</h3>
        <p class="text-caption">点击"新建用户"开始创建第一个用户</p>
      </div>

      <div v-else class="users-table-container">
        <table class="apple-table users-table">
          <thead>
            <tr>
              <th @click="sort('username')">
                用户名 
                <span class="sort-indicator" :class="getSortClass('username')">↕</span>
              </th>
              <th @click="sort('real_name')">
                真实姓名
                <span class="sort-indicator" :class="getSortClass('real_name')">↕</span>
              </th>
              <th>邮箱</th>
              <th>部门/职位</th>
              <th>角色</th>
              <th @click="sort('status')">
                状态
                <span class="sort-indicator" :class="getSortClass('status')">↕</span>
              </th>
              <th @click="sort('last_login_at')">
                最后登录
                <span class="sort-indicator" :class="getSortClass('last_login_at')">↕</span>
              </th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="user in users" 
              :key="user.id"
              @click="viewUserDetail(user)"
              class="user-row"
            >
              <td>
                <div class="user-info">
                  <div class="user-avatar">
                    <img 
                      v-if="user.avatar_url" 
                      :src="user.avatar_url" 
                      :alt="user.real_name"
                      class="avatar-image"
                    >
                    <div v-else class="avatar-placeholder">
                      {{ user.real_name?.charAt(0)?.toUpperCase() || '?' }}
                    </div>
                  </div>
                  <div class="user-details">
                    <div class="username">{{ user.username }}</div>
                    <div v-if="user.employee_id" class="employee-id">{{ user.employee_id }}</div>
                  </div>
                </div>
              </td>
              <td>
                <div class="real-name">{{ user.real_name }}</div>
              </td>
              <td>
                <div class="email">{{ user.email }}</div>
                <div v-if="user.phone" class="phone">{{ user.phone }}</div>
              </td>
              <td>
                <div v-if="user.department" class="department">{{ user.department }}</div>
                <div v-if="user.position" class="position">{{ user.position }}</div>
              </td>
              <td>
                <div class="roles">
                  <span 
                    v-for="role in user.roles" 
                    :key="role.id"
                    class="apple-tag apple-tag--primary role-tag"
                  >
                    {{ role.name }}
                  </span>
                  <span v-if="user.is_superuser" class="apple-tag apple-tag--warning">
                    超级用户
                  </span>
                </div>
              </td>
              <td>
                <span 
                  :class="['apple-tag', getStatusTagClass(user.status)]"
                >
                  {{ getStatusText(user.status) }}
                </span>
              </td>
              <td>
                <div v-if="user.last_login_at" class="login-info">
                  <div class="login-time">{{ formatDate(user.last_login_at) }}</div>
                </div>
                <div v-else class="text-caption">从未登录</div>
              </td>
              <td>
                <div class="action-buttons" @click.stop>
                  <button 
                    class="apple-button apple-button--text apple-button--small"
                    @click="editUser(user)"
                  >
                    编辑
                  </button>
                  <button 
                    v-if="user.status === 'active'"
                    class="apple-button apple-button--text apple-button--small"
                    @click="suspendUser(user)"
                  >
                    暂停
                  </button>
                  <button 
                    v-else-if="user.status === 'suspended'"
                    class="apple-button apple-button--text apple-button--small"
                    @click="activateUser(user)"
                  >
                    激活
                  </button>
                  <button 
                    class="apple-button apple-button--text apple-button--small"
                    @click="resetPassword(user)"
                  >
                    重置密码
                  </button>
                  <button 
                    class="apple-button apple-button--text apple-button--small apple-button--danger"
                    @click="deleteUser(user)"
                    :disabled="user.id === currentUserId"
                  >
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1" class="pagination">
      <button 
        class="apple-button apple-button--secondary"
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      
      <div class="page-numbers">
        <button
          v-for="page in visiblePages"
          :key="page"
          :class="['apple-button', currentPage === page ? 'apple-button--primary' : 'apple-button--secondary']"
          @click="changePage(page)"
        >
          {{ page }}
        </button>
      </div>
      
      <button 
        class="apple-button apple-button--secondary"
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
      
      <div class="page-info">
        <span class="text-caption">
          共 {{ total }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
        </span>
      </div>
    </div>

    <!-- 对话框组件 -->
    <UserCreateDialog
      v-model="showCreateDialog"
      @created="handleUserCreated"
    />

    <UserEditDialog
      v-model="showEditDialog"
      :user="selectedUser"
      @updated="handleUserUpdated"
    />

    <UserDetailDialog
      v-model="showDetailDialog"
      :user="selectedUser"
    />

    <PasswordResetDialog
      v-model="showPasswordDialog"
      :user="selectedUser"
      @reset="handlePasswordReset"
    />

    <UserStatisticsDialog
      v-model="showStatistics"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserCreateDialog from './components/UserCreateDialog.vue'
import UserEditDialog from './components/UserEditDialog.vue'
import UserDetailDialog from './components/UserDetailDialog.vue'
import PasswordResetDialog from './components/PasswordResetDialog.vue'
import UserStatisticsDialog from './components/UserStatisticsDialog.vue'
import { userApi } from '@/api/users'
import { useAuthStore } from '@/stores/auth'
import type { User } from '@/types/rbac'

// 状态管理
const authStore = useAuthStore()

// 响应式数据
const users = ref<User[]>([])
const loading = ref(false)
const searchQuery = ref('')
const filterDepartment = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const sortField = ref('created_at')
const sortOrder = ref('desc')

// 对话框状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showDetailDialog = ref(false)
const showPasswordDialog = ref(false)
const showStatistics = ref(false)
const selectedUser = ref<User | null>(null)

// 计算属性
const currentUserId = computed(() => authStore.user?.id)
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const departments = computed(() => {
  const depts = new Set(users.value.map(u => u.department).filter(Boolean))
  return Array.from(depts).sort()
})

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      sort_field: sortField.value,
      sort_order: sortOrder.value,
      ...(searchQuery.value && { search: searchQuery.value }),
      ...(filterDepartment.value && { department: filterDepartment.value }),
      ...(filterStatus.value && { status: filterStatus.value })
    }
    
    const response = await userApi.getUsers(params)
    
    if (response.success) {
      users.value = response.data
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

const sort = (field: string) => {
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortField.value = field
    sortOrder.value = 'asc'
  }
  loadUsers()
}

const getSortClass = (field: string) => {
  if (sortField.value !== field) return ''
  return sortOrder.value === 'asc' ? 'sort-asc' : 'sort-desc'
}

const changePage = (page: number) => {
  currentPage.value = page
  loadUsers()
}

const getStatusTagClass = (status: string) => {
  const classes = {
    'active': 'apple-tag--success',
    'inactive': 'apple-tag--warning',
    'suspended': 'apple-tag--danger',
    'locked': 'apple-tag--danger'
  }
  return classes[status as keyof typeof classes] || 'apple-tag'
}

const getStatusText = (status: string) => {
  const texts = {
    'active': '激活',
    'inactive': '未激活', 
    'suspended': '暂停',
    'locked': '锁定'
  }
  return texts[status as keyof typeof texts] || status
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

// 用户操作
const viewUserDetail = (user: User) => {
  selectedUser.value = user
  showDetailDialog.value = true
}

const editUser = (user: User) => {
  selectedUser.value = user
  showEditDialog.value = true
}

const resetPassword = (user: User) => {
  selectedUser.value = user
  showPasswordDialog.value = true
}

const suspendUser = async (user: User) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入暂停原因',
      '暂停用户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '请输入暂停原因'
      }
    )
    
    await userApi.suspendUser(user.id, reason)
    ElMessage.success('用户暂停成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('暂停用户失败:', error)
      ElMessage.error('暂停用户失败')
    }
  }
}

const activateUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要激活用户"${user.real_name}"吗？`,
      '激活用户',
      {
        confirmButtonText: '激活',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await userApi.activateUser(user.id)
    ElMessage.success('用户激活成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('激活用户失败:', error)
      ElMessage.error('激活用户失败')
    }
  }
}

const deleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${user.real_name}"吗？此操作不可撤销。`,
      '删除用户',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'apple-button--danger'
      }
    )
    
    await userApi.deleteUser(user.id)
    ElMessage.success('用户删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 事件处理
const handleUserCreated = () => {
  loadUsers()
  ElMessage.success('用户创建成功')
}

const handleUserUpdated = () => {
  loadUsers()
  ElMessage.success('用户更新成功')
}

const handlePasswordReset = () => {
  ElMessage.success('密码重置成功')
}

// 监听筛选条件变化
watch([filterDepartment, filterStatus], () => {
  currentPage.value = 1
  loadUsers()
})

// 组件挂载
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: var(--spacing-lg);
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: var(--spacing-xl);
  text-align: center;
}

.page-header .text-caption {
  margin-top: var(--spacing-sm);
  color: var(--text-secondary);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--spacing-lg);
  gap: var(--spacing-md);
}

.search-controls {
  display: flex;
  gap: var(--spacing-md);
  flex: 1;
  max-width: 800px;
}

.search-controls .apple-input {
  flex: 1;
}

.filter-select {
  min-width: 120px;
  flex-shrink: 0;
}

.action-controls {
  display: flex;
  gap: var(--spacing-sm);
  flex-shrink: 0;
}

.users-container {
  min-height: 400px;
}

.loading-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--apple-gray-5);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--spacing-md);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 64px;
  margin-bottom: var(--spacing-md);
  opacity: 0.5;
}

.users-table-container {
  overflow-x: auto;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-small);
}

.users-table {
  width: 100%;
  min-width: 1000px;
}

.users-table th {
  cursor: pointer;
  user-select: none;
  position: relative;
}

.users-table th:hover {
  background-color: var(--apple-gray-4);
}

.sort-indicator {
  margin-left: var(--spacing-xs);
  opacity: 0.3;
  transition: opacity var(--duration-fast);
}

.sort-asc .sort-indicator {
  opacity: 1;
  transform: rotate(180deg);
}

.sort-desc .sort-indicator {
  opacity: 1;
}

.user-row {
  cursor: pointer;
}

.user-row:hover {
  background-color: var(--bg-secondary);
}

.user-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: var(--color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
}

.user-details {
  min-width: 0;
}

.username {
  font-weight: 500;
  color: var(--text-primary);
}

.employee-id {
  font-size: 11px;
  color: var(--text-tertiary);
  font-family: 'SF Mono', Monaco, monospace;
}

.real-name {
  font-weight: 500;
}

.email {
  color: var(--text-primary);
}

.phone {
  font-size: 12px;
  color: var(--text-secondary);
}

.department {
  color: var(--text-primary);
}

.position {
  font-size: 12px;
  color: var(--text-secondary);
}

.roles {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-xs);
}

.role-tag {
  font-size: 10px;
}

.login-info {
  text-align: left;
}

.login-time {
  font-size: 12px;
  color: var(--text-primary);
}

.action-buttons {
  display: flex;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: var(--spacing-xl);
  gap: var(--spacing-sm);
  flex-wrap: wrap;
}

.page-numbers {
  display: flex;
  gap: var(--spacing-xs);
}

.page-info {
  margin-left: var(--spacing-md);
}

@media (max-width: 1200px) {
  .user-management {
    padding: var(--spacing-md);
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-controls {
    max-width: none;
    flex-wrap: wrap;
  }
  
  .action-controls {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .search-controls {
    flex-direction: column;
  }
  
  .filter-select {
    min-width: auto;
  }
  
  .action-controls {
    flex-direction: column;
  }
  
  .pagination {
    flex-direction: column;
    gap: var(--spacing-md);
  }
  
  .page-info {
    margin-left: 0;
  }
}
</style>